function charLimit(fid, countfield, maxlimit){
    $fid = $("#" + fid);
    
    if ($fid.val().length > maxlimit) {
        $fid.val($fid.val().substring(0, maxlimit));
    }
    else {
        $('#' + countfield).html(maxlimit - $fid.val().length);
    }
    return false;
}

function notEmpty(id){
    $id = $("#" + id);
    $val = $id.val();
    if ($val == "") {
        return false;
    }
    else {
        return true;
    }
}

function defaultText(){
    var alt = $(this).attr("alt"), txt = $(this).val();
    $.each(this, function(){
        $(this).focus(function(){
            $(this).val("");
        });
        $(this).blur(function(){
            if (txt == "" || txt == alt) 
                $(this).val(alt);
        });
    });
}

function resetForm(){
    $("form").find(':text,textarea').each(function(item){
        $(this).val("");
        $(this).empty();
    });
}

function max(arr){
    var $max = arr[0];
    for (var i = arr[1]; i < arr.length; i++) {
        if ($max < i) {
            $max = i;
        }
    }
    return $max;
}

function is_require_check(){
    var $entry = $("[mark='require']").parents(".form-entry:visible").has(":checkbox,:radio");
    var flag = true;
    $entry.each(function(){
        if ($(this).find(":checked").length == 0) {
            flag = false;
        }
    });
    return flag;
}

function is_require_select(){
	var $entry  = $("[mark='require']").parents(".form-entry:visible").has("select");
	var $select = $entry.find("select");
	var flag = true;
	if($select.val()==="0") flag = false;
	return flag;
}

function showErrMsg(msg,isappend){
	isappend? $("#err_info").append(msg):$("#err_info").html(msg);;
    $("#form_in").flip({
        direction: 'lr',
        color: "#fff",
        onEnd: function(){
            $("#input_form").fadeOut(0, function(){
                $("#form_out").fadeIn(300);
            });
        }
    });
}

function analizyData(data){
	
	var $ht = "";
	
	$ht+='<div class="vote_box"><p class="subject">调查结果</p>';
	
	for(var i=0;i<data.length;i++){
		var item  = data[i];
		var Value = item.Value;
		var Label = item.Label;
		
    	$ht+='<div class="polls"><div style=" font-size: 12px;font-weight: normal;line-height: 20px;overflow: hidden;padding-right: 0;text-align: left;word-wrap: break-word;">'+item.Question+'</div>';
    	
		for(var n=0;n<Label.length;n++){
			var item_ = '<div class="pitem">'+
			'<div class="psubject">'+Label[n]+'</div>'+
		    '<div class="barbg"><div class="bg" style="width:'+Math.floor(Value[n]/item.allValue*100)+'%;"></div></div>'+
		    '<div class="record">'+Math.floor(Value[n]/item.allValue*100)+'%</div>'+
		    '</div>';
			$ht+=item_;
		}
		
		$ht+='<div class="clear"></div><div class="alr"><a href="###" class="v_btn"></a></div></div>';
	}
	
	$ht+='</div>';
	
    return $ht;
}

$(function(){

    $("#submit_form").click(function(){
    	var type=$(this).attr("type");
        var $text = $("[mark='require']").parents(".form-entry").find('.widget_entry :text:not([mark="other"]),.widget_entry textarea');
        for (var i = 0; i < $text.length; i++) {
            if ($($text[i]).val() == "") {
                showErrMsg("你好像必填项没填哦！");
                return false;
            }
        }
		
        if (!is_require_check()) {
            showErrMsg("你好像必填项没填哦！");
            return false;
        }
        
		if(!is_require_select()){
			showErrMsg("你好像必填项没填哦！");
            return false;
		}
		
        $check_other = $(":checked[mark^='other']");
        for (var i = 0; i < $check_other.length; i++) {
            var $txt = $($check_other[i]).parent('li').find(":text[mark='other']");
            if ($txt.val() == "") {
                showErrMsg("列表问题的“其他”项没有填写哦！");
                return false;
            }
        }
        
        $form = $(this).parents("form");
        $.ajax({
            url: $form.attr('action'),
            type: "POST",
			dataType:"json",
            data: $form.serialize(),
            success: function(data){
				if(data.status)
				{
					$("#go_back").remove();
					
					if(type==="feedback")
					{
						$("#form_out").css("background","none");
						if(data.entries){
							showErrMsg(analizyData(data.entries));
						}else{
							var item = '<div class="vote_box"><p class="subject">调查结果</p><div class="polls">赶快来投票吧<div class="clear"></div><div class="alr"><a href="###" class="v_btn"></a></div></div></div>';
							showErrMsg(item);
						}
						
						resetForm();
					}
					else
					{
						showErrMsg(data.info);
						resetForm();
					}
				}
				else
				{
					showErrMsg(data.info);
				}
               
            },
            error: function(data){
                showErrMsg(data.info);
            }
        });
        
    });
    
    var first_jump;
    $(".form-entry[is_Goto='1']").each(function(){
        $cur_id = parseInt($(this).attr('entry_id'));
        $position = parseInt($(this).attr('id')) + 1;
        $entry_num = $(".form-entry").length;
        
        var page = [];
        $(":radio[name='" + $cur_id + "']").each(function(){
            if ($(this).attr('gotopage')) {
                page.push($(this).attr('gotopage'));
            }
        });
        var maxPageNum = max(page);
        
        $(":radio[name=" + $cur_id + "]").click(function(){
            if ($(this).is(":checked")) {
                var curent_pos = parseInt($(this).parents(".form-entry").attr("id")) + 1;
                var gotopage = parseInt($(this).attr('gotopage'));
                $(".form-entry[id]").each(function(){
                    var pos = parseInt($(this).attr("id")) + 1;
                    var uppers = [];
                    var downs = [];
                    if ((curent_pos < pos) && (pos < gotopage)) {
                        uppers.push(this);
                    }
                    else {
                        downs.push(this);
                    }
                    $(uppers).slideUp(0, function(){
                        $(uppers).each(function(){
                            if ($(this).attr("is_Goto") == '1') {
                                $(this).find(":radio").removeAttr('checked');
                            }
                        });
                    });
                    $(downs).slideDown(60);
                    
                });
                
            }
        });
        
    });
    first_jump = $(".form-entry[is_Goto='1']").eq(0).attr("entry_id");
    $(":radio[name=" + first_jump + "]:checked").triggerHandler('click');
    $("#back_btn").click(function(){
        $("#form_in").flip({
            direction: 'rl',
            color: "#fff",
            onEnd: function(){
                $("#form_out").fadeOut(0, function(){
                    $("#input_form").fadeIn(300);
                });
            }
        });
        return false;
    });
});
